package com.ruoyi.mobile.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.security.utils.DictUtils;
import com.ruoyi.mobile.domain.ShOrderEntity;
import com.ruoyi.mobile.domain.ShProductEntity;
import com.ruoyi.mobile.domain.ShProductPictureEntity;
import com.ruoyi.mobile.mapper.IShOrderMapper;
import com.ruoyi.mobile.mapper.IShProductMapper;
import com.ruoyi.mobile.mapper.IShProductPictureMapper;
import com.ruoyi.mobile.utils.NftResponse;
import com.ruoyi.mobile.utils.Paginator;
import com.ruoyi.mobile.utils.QueryUtil;
import com.ruoyi.mobile.utils.ResponseConstants;
import com.ruoyi.system.api.domain.SysDictData;
import com.ruoyi.system.api.req.ShProductReq;
import com.ruoyi.system.api.resp.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import com.ruoyi.mobile.service.IShProductService;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 商品信息Service业务层处理
 * 
 * @author ruoyi
 * @date 2023-07-18
 */
@Service
public class ShProductServiceImpl extends ServiceImpl<IShProductMapper, ShProductEntity> implements IShProductService {
    @Resource
    private StringRedisTemplate myRedisTemplate;
    @Autowired
    private IShProductPictureMapper productPictureMapper;
    @Autowired
    private IShOrderMapper orderMapper;

    @Override
    public NftResponse<List<DictResp>> getProductTypes() {
        Map<Object, Object> mapValue = myRedisTemplate.opsForHash().entries("PRODUCTTYPE");
        List<DictResp> listResult = new ArrayList<>();
        if (mapValue.isEmpty()) {
            List<DictResp> dictList = this.baseMapper.selectDictByType("product_type");
            mapValue = new HashMap<>();
            for (DictResp obj:dictList) {
                listResult.add(obj);
            }
            myRedisTemplate.opsForHash().putAll("PRODUCTTYPE", mapValue);
        }else {
            for (Map.Entry<Object, Object> entry : mapValue.entrySet()) {
                DictResp resp = JSON.parseObject(entry.getValue().toString().replaceAll("\\\\",""), DictResp.class);
                listResult.add(resp);
            }
        }
        return new NftResponse<>(ResponseConstants.SUCCESS_CODE, "获取成功", listResult);
    }

    @Override
    public NftResponse<List<DictResp>> getMealTypes() {
        Map<Object, Object> mapValue = myRedisTemplate.opsForHash().entries("MEALTYPE");
        List<DictResp> listResult = new ArrayList<>();
        if (mapValue.isEmpty()) {
            List<DictResp> dictList = this.baseMapper.selectMealByType("product_type");
            mapValue = new HashMap<>();
            for (DictResp obj:dictList) {
                listResult.add(obj);
            }
            myRedisTemplate.opsForHash().putAll("MEALTYPE", mapValue);
        }else {
            for (Map.Entry<Object, Object> entry : mapValue.entrySet()) {
                DictResp resp = JSON.parseObject(entry.getValue().toString().replaceAll("\\\\",""), DictResp.class);
                listResult.add(resp);
            }
        }
        return new NftResponse<>(ResponseConstants.SUCCESS_CODE, "获取成功", listResult);
    }

    @Override
    public NftResponse<List<DictResp>> getTrainTypes() {
        Map<Object, Object> mapValue = myRedisTemplate.opsForHash().entries("TRAINTYPE");
        List<DictResp> listResult = new ArrayList<>();
        if (mapValue.isEmpty()) {
            List<DictResp> dictList = this.baseMapper.selectTrainByType("product_type");
            mapValue = new HashMap<>();
            for (DictResp obj:dictList) {
                listResult.add(obj);
            }
            myRedisTemplate.opsForHash().putAll("TRAINTYPE", mapValue);
        }else {
            for (Map.Entry<Object, Object> entry : mapValue.entrySet()) {
                DictResp resp = JSON.parseObject(entry.getValue().toString().replaceAll("\\\\",""), DictResp.class);
                listResult.add(resp);
            }
        }
        return new NftResponse<>(ResponseConstants.SUCCESS_CODE, "获取成功", listResult);
    }

    @Override
    public NftResponse<Paginator<ShProductResp>> getProductList(ShProductReq query) {
        if (query.getPageNo() == null || query.getPageNo() <= 0) {
            return new NftResponse<>(ResponseConstants.ERROR_CODE, "入参页码错误", null);
        }
        if (query.getPageSize() == null || query.getPageSize() <= 0) {
            return new NftResponse<>(ResponseConstants.ERROR_CODE, "入参每页数量错误", null);
        }
        List<SysDictData> dictLList = DictUtils.getDictCache("product_label");
        HashMap<String, String> dictLMap = new HashMap<>();
        for (SysDictData data:dictLList) {
            dictLMap.put(data.getDictValue(),data.getDictLabel());
        }
        Paginator<ShProductResp> paginator = new Paginator<ShProductResp>(query.getPageNo(), query.getPageSize(), 0, new ArrayList<>());
        QueryWrapper<ShProductEntity> wrapperQuery = new QueryWrapper<>();
        if (null!=query.getProductType()&&query.getProductType()>0) {
            wrapperQuery.eq(QueryUtil.camelToUnderline("productType"), query.getProductType());
        }
        if (null!=query.getShopId()) {
            wrapperQuery.eq(QueryUtil.camelToUnderline("shopId"), query.getShopId());
        }
        if (null!=query.getAppid()&&!"".equals(query.getAppid())) {
            wrapperQuery.eq(QueryUtil.camelToUnderline("appId"),query.getAppid());
        }
        wrapperQuery.le(QueryUtil.camelToUnderline("productType"), 80);
        wrapperQuery.orderByAsc("order_num");
        IPage<ShProductEntity> page = new Page<>(query.getPageNo(),query.getPageSize());
        IPage<ShProductEntity> pageRtn = this.baseMapper.selectPage(page,wrapperQuery);
        List<ShProductEntity> list = pageRtn.getRecords();
        List<ShProductResp> result = BeanUtil.copyToList(list, ShProductResp.class);
        for (ShProductResp obj:result) {
            QueryWrapper<ShProductPictureEntity> wrapperQueryPic = new QueryWrapper<>();
            wrapperQueryPic.eq(QueryUtil.camelToUnderline("productId"), obj.getId());
            wrapperQueryPic.eq(QueryUtil.camelToUnderline("isVideo"), 0);
            wrapperQueryPic.last("limit 1");
            List<ShProductPictureEntity> listPic = productPictureMapper.selectList(wrapperQueryPic);
            if (null!=listPic&&listPic.size()>0) {
                obj.setProductPic(listPic.get(0).getProductPic());
            }
            StringBuffer labelName = new StringBuffer();
            if (null != obj.getLabelId() && !"".equals(obj.getLabelId())) {
                String[] labelIdAry = obj.getLabelId().split(",");
                for (String labelId : labelIdAry) {
                    labelName.append(dictLMap.get(labelId)).append(",");
                }
            }
            obj.setLabelNames(labelName.toString());
        }
        paginator.setPageNo(query.getPageNo());
        paginator.setPageSize(query.getPageSize());
        paginator.setTotalDataNum(pageRtn.getTotal());
        paginator.setPageData(result);
        return new NftResponse<>(ResponseConstants.SUCCESS_CODE, "获取成功", paginator);
    }

    @Override
    public NftResponse<Paginator<ShProductResp>> getMealList(ShProductReq query) {
        if (query.getPageNo() == null || query.getPageNo() <= 0) {
            return new NftResponse<>(ResponseConstants.ERROR_CODE, "入参页码错误", null);
        }
        if (query.getPageSize() == null || query.getPageSize() <= 0) {
            return new NftResponse<>(ResponseConstants.ERROR_CODE, "入参每页数量错误", null);
        }
        List<SysDictData> dictLList = DictUtils.getDictCache("product_label");
        HashMap<String, String> dictLMap = new HashMap<>();
        for (SysDictData data:dictLList) {
            dictLMap.put(data.getDictValue(),data.getDictLabel());
        }
        Paginator<ShProductResp> paginator = new Paginator<ShProductResp>(query.getPageNo(), query.getPageSize(), 0, new ArrayList<>());
        QueryWrapper<ShProductEntity> wrapperQuery = new QueryWrapper<>();
        if (null!=query.getProductType()&&query.getProductType()>0) {
            wrapperQuery.eq(QueryUtil.camelToUnderline("productType"), query.getProductType());
        }
        if (null!=query.getShopId()) {
            wrapperQuery.eq(QueryUtil.camelToUnderline("shopId"), query.getShopId());
        }
        if (null!=query.getAppid()&&!"".equals(query.getAppid())) {
            wrapperQuery.eq(QueryUtil.camelToUnderline("appId"),query.getAppid());
        }
        wrapperQuery.gt(QueryUtil.camelToUnderline("productType"), 90);
        wrapperQuery.orderByAsc("order_num");
        IPage<ShProductEntity> page = new Page<>(query.getPageNo(),query.getPageSize());
        IPage<ShProductEntity> pageRtn = this.baseMapper.selectPage(page,wrapperQuery);
        List<ShProductEntity> list = pageRtn.getRecords();
        List<ShProductResp> result = BeanUtil.copyToList(list, ShProductResp.class);
        for (ShProductResp obj:result) {
            QueryWrapper<ShProductPictureEntity> wrapperQueryPic = new QueryWrapper<>();
            wrapperQueryPic.eq(QueryUtil.camelToUnderline("productId"), obj.getId());
            wrapperQueryPic.eq(QueryUtil.camelToUnderline("isVideo"), 0);
            wrapperQueryPic.last("limit 1");
            List<ShProductPictureEntity> listPic = productPictureMapper.selectList(wrapperQueryPic);
            if (null!=listPic&&listPic.size()>0) {
                obj.setProductPic(listPic.get(0).getProductPic());
            }
            StringBuffer labelName = new StringBuffer();
            if (null != obj.getLabelId() && !"".equals(obj.getLabelId())) {
                String[] labelIdAry = obj.getLabelId().split(",");
                for (String labelId : labelIdAry) {
                    labelName.append(dictLMap.get(labelId)).append(",");
                }
            }
            obj.setLabelNames(labelName.toString());
        }
        paginator.setPageNo(query.getPageNo());
        paginator.setPageSize(query.getPageSize());
        paginator.setTotalDataNum(pageRtn.getTotal());
        paginator.setPageData(result);
        return new NftResponse<>(ResponseConstants.SUCCESS_CODE, "获取成功", paginator);
    }

    @Override
    public NftResponse<Paginator<ShProductResp>> getTrainList(ShProductReq query) {
        if (query.getPageNo() == null || query.getPageNo() <= 0) {
            return new NftResponse<>(ResponseConstants.ERROR_CODE, "入参页码错误", null);
        }
        if (query.getPageSize() == null || query.getPageSize() <= 0) {
            return new NftResponse<>(ResponseConstants.ERROR_CODE, "入参每页数量错误", null);
        }
        List<SysDictData> dictLList = DictUtils.getDictCache("product_label");
        HashMap<String, String> dictLMap = new HashMap<>();
        for (SysDictData data:dictLList) {
            dictLMap.put(data.getDictValue(),data.getDictLabel());
        }
        Paginator<ShProductResp> paginator = new Paginator<ShProductResp>(query.getPageNo(), query.getPageSize(), 0, new ArrayList<>());
        QueryWrapper<ShProductEntity> wrapperQuery = new QueryWrapper<>();
        if (null!=query.getProductType()&&query.getProductType()>0) {
            wrapperQuery.eq(QueryUtil.camelToUnderline("productType"), query.getProductType());
        }
        if (null!=query.getShopId()) {
            wrapperQuery.eq(QueryUtil.camelToUnderline("shopId"), query.getShopId());
        }
        if (null!=query.getAppid()&&!"".equals(query.getAppid())) {
            wrapperQuery.eq(QueryUtil.camelToUnderline("appId"),query.getAppid());
        }
        wrapperQuery.gt(QueryUtil.camelToUnderline("productType"), 80);
        wrapperQuery.le(QueryUtil.camelToUnderline("productType"), 90);
        wrapperQuery.orderByAsc("order_num");
        IPage<ShProductEntity> page = new Page<>(query.getPageNo(),query.getPageSize());
        IPage<ShProductEntity> pageRtn = this.baseMapper.selectPage(page,wrapperQuery);
        List<ShProductEntity> list = pageRtn.getRecords();
        List<ShProductResp> result = BeanUtil.copyToList(list, ShProductResp.class);
        for (ShProductResp obj:result) {
            QueryWrapper<ShProductPictureEntity> wrapperQueryPic = new QueryWrapper<>();
            wrapperQueryPic.eq(QueryUtil.camelToUnderline("productId"), obj.getId());
            wrapperQueryPic.eq(QueryUtil.camelToUnderline("isVideo"), 0);
            wrapperQueryPic.last("limit 1");
            List<ShProductPictureEntity> listPic = productPictureMapper.selectList(wrapperQueryPic);
            if (null!=listPic&&listPic.size()>0) {
                obj.setProductPic(listPic.get(0).getProductPic());
            }
            StringBuffer labelName = new StringBuffer();
            if (null != obj.getLabelId() && !"".equals(obj.getLabelId())) {
                String[] labelIdAry = obj.getLabelId().split(",");
                for (String labelId : labelIdAry) {
                    labelName.append(dictLMap.get(labelId)).append(",");
                }
            }
            obj.setLabelNames(labelName.toString());
        }
        paginator.setPageNo(query.getPageNo());
        paginator.setPageSize(query.getPageSize());
        paginator.setTotalDataNum(pageRtn.getTotal());
        paginator.setPageData(result);
        return new NftResponse<>(ResponseConstants.SUCCESS_CODE, "获取成功", paginator);
    }

    @Override
    public NftResponse<ShProductResp> getProductInfo(Long id, Long userId) {
        ShProductEntity entity = this.baseMapper.selectById(id);
        ShProductResp rtn = BeanUtil.copyProperties(entity, ShProductResp.class);
        QueryWrapper<ShProductPictureEntity> wrapperQueryPic = new QueryWrapper<>();
        wrapperQueryPic.eq(QueryUtil.camelToUnderline("productId"), id);
        List<ShProductPictureEntity> listPic = productPictureMapper.selectList(wrapperQueryPic);
        if (null!=listPic&&listPic.size()>0) {
            List<ShProductPictureResp> listPicRps = BeanUtil.copyToList(listPic, ShProductPictureResp.class);
            for (ShProductPictureResp pic:listPicRps) {
                if (pic.getIsVideo()==0) {
                    rtn.setProductPic(pic.getProductPic());
                    break;
                }
            }
            rtn.setProductPics(listPicRps);
        }
        List<SysDictData> dictLList = DictUtils.getDictCache("product_label");
        HashMap<String, String> dictLMap = new HashMap<>();
        for (SysDictData data:dictLList) {
            dictLMap.put(data.getDictValue(),data.getDictLabel());
        }
        StringBuffer labelName = new StringBuffer();
        if (null != rtn.getLabelId() && !"".equals(rtn.getLabelId())) {
            String[] labelIdAry = rtn.getLabelId().split(",");
            for (String labelId : labelIdAry) {
                labelName.append(dictLMap.get(labelId)).append(",");
            }
        }
        rtn.setLabelNames(labelName.toString());
        QueryWrapper<ShOrderEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(QueryUtil.camelToUnderline("product_id"), id);
        wrapper.eq(QueryUtil.camelToUnderline("status"), 1);
        wrapper.eq(QueryUtil.camelToUnderline("create_by"), userId);
        List<ShOrderEntity> orderList = orderMapper.selectList(wrapper);
        if (null!=orderList&&orderList.size()>0) {
            rtn.setPay(true);
        }else {
            rtn.setPay(false);
        }
        return new NftResponse<>(ResponseConstants.SUCCESS_CODE, "查询成功", rtn);
    }
}
